from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import ListAPIView
from cart.models import CartModel
from user.models import UserModel
from cart.cartser import CartSerializer
from utils.authorization import MyAuthentication
from order import models,orderser

# Create your views here.
class CartView(ListAPIView):
  queryset = CartModel.objects.all()
  serializer_class = CartSerializer
  authentication_classes = [MyAuthentication]
  def get_queryset(self):
      user= self.request.query_params.get("user")
      if user:
          return self.queryset.filter(user=user,select=True)

#优惠列表的接口
class CouponView(APIView):
    authentication_classes = [MyAuthentication]
    def get(self,request):
        user=request.query_params.get("user")
        userinfo=UserModel.objects.get(id=user)
        mycoupon=models.UserCoupon.objects.filter(user=user)
        ser=orderser.UserCouponSerializer(instance=mycoupon,many=True)
        return Response({"code":200,"msg":"请求成功","data":{"credit":userinfo.credit,"tomoney":10,"coupon":ser.data}})

from utils.myredis import redistoll
#生成订单号 时间+四位随机数
import random
import time
#导入事务
from django.db import transaction
def get_order_number():
    order_number = "JD"+str(time.strftime('%Y%m%d%H%M%S')) + str(random.randint(1000,9999))
    return order_number


#生成订单
class Order(APIView):
    authentication_classes = [MyAuthentication]
    def post(self,request):
        user=request.data.get('user')
        order=redistoll.getstr(user)
        if order:
            return Response({"code":200,"msg":"你的订单存在请勿重复提交"})
        #开启事务的保存点
        transac=transaction.savepoint()
        try:
            #1 订单号
            orderdata={
                "orderno":get_order_number(),
                "user":user,
                "score":request.data.get('score',0),
                "coupon":request.data.get('coupon',None),
                "paytype":request.data.get('paytype',1),
            }
            #总价 去购物车拿当前用户选中的数据 做一个累加
            cart=CartModel.objects.filter(user=user,select=True)
            total=0
            for item in cart:
                total+=item.course.discount
            orderdata['totalprice']=total
            orderdata['payprice']=total
            #计算实际支付的价格
            if orderdata['score']!=0:
                orderdata['payprice']=float(orderdata['totalprice'])-orderdata['score']/10
            if orderdata['coupon']!=None:
                cou=models.UserCoupon.objects.filter(id=orderdata['coupon']).first()#当前选择的优惠券
                if cou.isshow:
                    orderdata['payprice']=orderdata['totalprice']-cou.coupon.price
            ordser=orderser.OrderSerializer(data=orderdata)
            if ordser.is_valid():
                ordser.save()
            #将订单号存储到redis 用户id名为key 订单号为value
                redistoll.setstrno(user,orderdata['orderno'])
                #操作订单详情表
                for item in cart:
                    detail={
                        "order":ordser.data.get("id"),
                        "course":item.course.id,
                        "price":item.course.price,
                        "discount":item.course.discount,
                        "cover":"http://127.0.0.1:8000/uploads/"+str(item.course.cover),
                        "cname":item.course.cname,
                    }
                    detailser=orderser.OrderDetailSerializer(data=detail)
                    if detailser.is_valid():
                        detailser.save()
                    else:
                        return Response(detailser.errors)
                    #删除购物车
                    item.delete()
            else:
                return Response(ordser.errors)
            #移除redis数据
            redistoll.delkey(user)
            #事务的提交
            transaction.savepoint_commit(transac)
            return Response({"msg":"订单生成成功","id":ordser.data.get("id"),"timeout":30})
        except:
            #设置事务的回滚
            transaction.savepoint_rollback(transac)
            return Response({"msg":"订单生成失败"})

from utils.Alipay import AliPaySDK
#生成支付链接的接口
class AliPayLink(APIView):
    authentication_classes = [MyAuthentication]
    def get(self,request):
        oid=request.query_params.get("order")
        order=models.OrderModel.objects.filter(id=oid).first()
        if order:
            ali=AliPaySDK()
            return Response(ali.page_pay(order.orderno,order.payprice,"向浮光付款"))
        else:
            return Response({"msg":"订单不存在"})


#处理支付成功后的结果
class AliPayResult(APIView):
    def get(self,request):
        #获取到支付宝返回的参数
        ali = AliPaySDK()
        result=ali.check_sign(request.query_params.dict())
        if result:
            #获取到订单号 根据订单修改状态  支付流水  支付时间
            order=models.OrderModel.objects.filter(orderno=request.query_params.get("out_trade_no")).first()
            order.status=1
            order.payno=request.query_params.get('trade_no')
            order.paytime=request.query_params.get('timestamp')
            order.save()
            #看是否使用了积分  使用了积分 会员表减积分
            if order.score:
                #去用户表中修改积分
                user=UserModel.objects.filter(id=order.user.id).first()
                user.credit=user.credit-order.score
                user.save()
            # 看是否使用了优惠券  使用了优惠券 会员优惠券表修改状态
            if order.coupon:
                coupon=models.UserCoupon.filter(id=order.coupon).first()
                coupon.isshow=False
                coupon.save()
            #返回给用户数据
            course=models.OrderDetailModel.objects.filter(order=order.id)
            ser=orderser.OrderDetailSerializer(course,many=True)
            #将当前的课程信息存储我的课程中
            for item in course:
                mydata={
                    "user":order.user.id,#用户id
                    "course":item.course.id,#课程id
                    "cname":item.course.cname,#课程名称
                    "price":item.course.price,#课程价格
                    "discount":item.course.discount,#课程折扣
                    "cover":str(item.course.cover),#课程支付价格
                }
                myser=orderser.MyCourseSerializer(data=mydata)
                if myser.is_valid():
                    myser.save()
                else:
                    return Response({"msg":myser.errors})
            return Response({"msg":"支付成功","course":ser.data,"paytime":order.paytime,"payprice":order.payprice})
        else:
            return Response({"msg":"支付失败"})

#我的课程
class MyCourseView(APIView):
    def get(self,request):
        user=request.query_params.get("user")
        info=models.MyCourseModel.objects.filter(user=user)
        ser=orderser.MyCourseSerializer(instance=info,many=True)
        return Response(ser.data)
#我的订单
#设置订单分页 以及检索
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
class OrderPagination(PageNumberPagination):
    page_size=2
    page_size_query_param='size'
    page_query_param='page'
class MyOrderView(ListAPIView):
    queryset=models.OrderModel.objects.all()
    serializer_class=orderser.OrderSerializer
    pagination_class=OrderPagination
    def get_queryset(self):
        status=self.request.query_params.get('status')
        user=self.request.query_params.get("user")
        #print(user,status)
        if int(status)==-1:
            return self.queryset.filter(user=user)
        else:
            return self.queryset.filter(user=user,status=status)


class StatusView(APIView):
    def get(self,request):
        #['未支付','已支付','已完成']
        return Response([{'id':0,'name':'未支付'},{'id':1,'name':'已支付'},{'id':2,'name':'已完成'}])

